import React from 'react';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Row, Col } from 'antd';
import { connect } from 'dva';
import { ModalC, TableC, InputNumberC } from '../../../../comps';
import debounce from 'lodash/debounce';
import ico from '../../../../assets/busi/workStation/Barra/double_arrow_icon.png';
import style from './index.less';
import moment from 'moment';
@Form.create()
class poolExportC extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      poolName: [], //券池左侧数据
      tableData: [], //券池右侧数据
      selectedRowKeys: [], //券池左侧已选择key
      selectedRowKeys1: [], //券池右侧已选择key
      newPoolColumns: [], //券池右侧列头
      currentPage: 1,
    };
    this.dataSource = {}; //保存右侧数据
    this.amountChange = debounce(this.amountChange, 500);
  }

  componentDidMount() {
    const {
      dispatch,
      workStationM: { poolColumns1 },
    } = this.props;
    //获取券池名称下拉框
    dispatch({
      type: 'couponPoolQueryM/findName',
      payload: {
        assetClassId: 'stock',
      },
      callback: (res) => {
        this.setState({
          poolName: res.data.dataSource, // 券池名称下拉框内容
          newPoolColumns: poolColumns1,
        });
      },
    });
    this.changeColumns;
  }
  // 券池左侧点击
  onSelectChange = (selectedRowKeys, selectedRows) => {
    if (selectedRowKeys.length > this.state.selectedRowKeys.length) {
      this.props.dispatch({
        type: 'couponPoolQueryM/findAll',
        payload: {
          securityPoolId: selectedRowKeys[selectedRowKeys.length - 1],
        },
        callback: (res) => {
          if (res) {
            this.dataSource[selectedRowKeys[selectedRowKeys.length - 1]] = res.data.dataSource;
            this.setState({
              tableData: [...this.state.tableData, ...res.data.dataSource],
            });
          }
        },
      });
    } else {
      let deleteKey = '';
      let newDataSource = [];
      this.state.selectedRowKeys.map((i) => {
        if (!selectedRowKeys.some((val) => val == i)) {
          deleteKey = i;
        }
      });
      delete this.dataSource[deleteKey];
      for (let key in this.dataSource) {
        newDataSource.push(...this.dataSource[key]);
      }
      this.setState({
        tableData: newDataSource,
      });
    }
    this.setState({
      selectedRowKeys,
      selectedRows,
    });
    this.changeColumns();
  };
  // 券池右侧点击
  onSelectChange1 = (selectedRowKeys1, selectedRows1) => {
    const { tableData } = this.state;
    tableData.map((i) => {
      if (selectedRows1.some((val) => val.id == i.id)) {
        i.isEdit = true;
      } else {
        i.isEdit = false;
        if (i.amount) delete i.amount;
      }
    });
    this.setState({
      selectedRowKeys1,
      selectedRows1,
    });
    this.changeColumns();
  };
  // 改变券池列展示
  changeColumns = () => {
    const {
      workStationM: { poolColumns1 },
    } = this.props;
    poolColumns1.map((item) => {
      if (item.key == 'amount') {
        item.render = (val, record) => {
          if (record.isEdit) {
            return (
              <InputNumberC
                form={this.props.form}
                dataIndex={`amount${record.id}`}
                initialValue={val ? val : ''}
                precision={0}
                splitStyle={true}
                min={0}
                onChange={(e) => this.amountChange(e, record.id)}
                rules={[{ required: true, message: ' ' }]}
                size={[{ size: 'small' }]}
              />
            );
          } else {
            if (val == null || val === undefined || val === '') {
              return '--';
            } else {
              // NaN: Not a Number
              // isNaN()的缺点就在于 null、空格以及空串会被按照0来处理
              if (isNaN(val)) {
                return val;
              } else {
                return Number(val);
              }
            }
          }
        };
      }
    });

    this.setState({ newPoolColumns: poolColumns1 });
  };
  // 交易数量改变
  amountChange = (e, id) => {
    this.state.tableData.map((i) => {
      if (i.id == id) {
        i.amount = e;
      }
    });
  };

  //表格页码响应
  handleTableChange = (pagination) => {
    const { current } = pagination;
    this.setState({
      currentPage: current,
    });
  };
  // 模态框内容
  addForm = () => {
    const {
      workStationM: { poolColumns },
      loading,
    } = this.props;
    const { poolName, tableData, selectedRowKeys, selectedRowKeys1, newPoolColumns, currentPage } = this.state;

    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
      onSelectAll: this.onSelectAll,
      columnTitle: ' ',
    };
    const rowSelection1 = {
      selectedRowKeys1,
      onChange: this.onSelectChange1,
      columnTitle: ' ',
    };
    return (
      <div>
        <Row>
          <Col span={6}>
            <div className={style.modalTable}>
              <TableC
                columns={poolColumns || []}
                dataSource={poolName || []}
                rowSelection={rowSelection}
                scroll={{ y: 378 }}
                loading={loading.effects['couponPoolQueryM/findName']}
                rowKey={'id'}
                hidePage={true}
              />
            </div>
          </Col>
          <Col span={2}>
            <div style={{ textAlign: 'center', marginTop: '131px' }}>
              <img src={ico} />
            </div>
          </Col>
          <Col span={16}>
            <div className={style.modalTable}>
              <TableC
                columns={newPoolColumns || []}
                dataSource={tableData || []}
                rowSelection={rowSelection1}
                scroll={{ y: 320 }}
                loading={loading.effects['couponPoolQueryM/findAll']}
                rowKey={'id'}
                size={'small'}
                simple={true}
                onChange={this.handleTableChange}
                current={currentPage}
              />
            </div>
          </Col>
        </Row>
      </div>
    );
  };

  // 确认
  addanOK = () => {
    const {
      form: { validateFields },
      tableData,
    } = this.props;
    validateFields((err, fieldsValue) => {
      if (!err) {
        let arr = tableData.map((i) => {
          return {
            amount: i.holdingNum,
            // tradingCode: i.securitiesCode?.split('.')[0],
            tradingCode: i.securitiesCode,

            type: '0',
            holdingDate: moment(this.props.date).format('YYYY-MM-DD'),
            exchangeCode: i.exchangeCode,
          };
        });
        let holdingInfos = [];
        this.state.selectedRowKeys1.map((i) => {
          this.state.tableData.map((val) => {
            if (i == val.id) {
              holdingInfos.push({
                amount: val.amount,
                tradingCode: val.stockCode,
                type: '0',
                holdingDate: moment(this.props.date).format('YYYY-MM-DD'),
                exchangeCode: val.exchangeCode,
              });
            }
          });
        });
        //需要合并原页面表格的数据，重叠的叠加数量，没有的添加,
        //     arr.map(item=>{
        //         holdingInfos.map((hold)=>{
        //             if(hold.tradingCode==item.tradingCode){
        //                 item.amount=item.amount+hold.amount;
        //                 hold.flag='1'
        //             }
        //         })
        //     })
        //     let temp = arr.concat(holdingInfos)
        //    let myData= temp.filter(item=>item.flag!='1')
        //    console.log(myData)

        // return;
        this.props.dispatch({
          type: 'workStationM/poolExport',
          payload: {
            portfolioId: this.props.productCode,
            holdingInfos: arr.concat(holdingInfos),
          },
          callback: (res) => {
            if (res) {
              this.props.poolOk();
            }
          },
        });
      }
    });
  };

  // 取消
  addanCancel = () => {
    this.props.changeVisible();
  };

  render() {
    return (
      <div className={style.modal}>
        <ModalC
          title={'券池导入'}
          visible={this.props.visible}
          maskClosable={false}
          onOk={this.addanOK}
          onCancel={this.addanCancel}
          confirmLoading={this.props.loading.effects['workStationM/poolExport'] === true}
          width={668}
          height={414}
        >
          <div>{this.addForm()}</div>
        </ModalC>
      </div>
    );
  }
}
export default connect(({ workStationM, loading, couponPoolQueryM }) => ({ workStationM, loading, couponPoolQueryM }))(poolExportC);
